<?php

use think\facade\Db;

function success($data = [], $msg = '操作成功')
{
    return json([
        'code' => 1,
        'msg' => $msg,
        'data' => $data
    ]);
}

function error($msg = '操作失败', $code = 400, $data = [])
{
    return json([
        'code' => 0,
        'msg' => $msg,
        'data' => $data
    ]);
}

function createRandStr($length = 8)
{
    $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $randStr = '';
    for ($i = 0; $i < $length; $i++) {
        $randStr .= $str[mt_rand(0, strlen($str) - 1)];
    }
    return $randStr;
}

function signToken($userId, $mobile)
{
    $data = [
        // 签发人
        'iss' => request()->domain(),
        // 签发时间
        'iat' => time(),
        // 自定义数据
        'data' => [
            'user_id' => $userId,
            'mobile' => $mobile,
        ]
    ];
    $key = config('app.jwt_key');
    $token = \Firebase\JWT\JWT::encode($data, $key, 'HS256');
    return $token;
}

function checkSmsCode($mobile, $code)
{
    $log = Db::name('sms_code_log')->where('mobile', $mobile)->find();
    if (!$log) {
        return false;
    }
    if ($log['code'] != $code) {
        return false;
    }
    if (time() - $log['send_time'] > 300) {
        Db::name('sms_code_log')->where('mobile', $mobile)->delete();
        return false;
    }
    Db::name('sms_code_log')->where('mobile', $mobile)->delete();
    return true;
}

